package com.nuorui.module.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nuorui.common.core.domain.ResponseDTO;
import com.nuorui.module.system.mapper.RoleUserMapper;
import com.nuorui.module.system.domain.entity.RoleUserEntity;
import com.nuorui.module.system.domain.form.RoleUserForm;
import com.nuorui.module.system.domain.vo.RoleVO;
import com.nuorui.module.system.domain.vo.UserVO;
import com.nuorui.module.system.service.RoleUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 角色关联用户
 *
 * @author: Fred
 * @email 453086@qq.com
 * @create: 2025-06-12 09:01
 */
@Slf4j
@Service
public class RoleUserServiceImpl  extends ServiceImpl<RoleUserMapper, RoleUserEntity> implements RoleUserService {


    @Override
    public ResponseDTO<List<UserVO>> getUsersByRoleId(Long roleId) {
        return ResponseDTO.ok(baseMapper.selectUsersByRoleId(roleId));
    }

    @Override
    public ResponseDTO<String> batchSave(Long roleId, RoleUserForm roleUserForm) {

        // 已选择的员工id列表
        Set<Long> selectedUserIdList = roleUserForm.getUserIdList();

        // 数据库里已有的员工id列表
        List<UserVO> dbUserList = baseMapper.selectUsersByRoleId(roleId);
        Set<Long> dbEmployeeIdSet = dbUserList.stream().map(UserVO::getUserId).collect(Collectors.toSet());
        // 从已选择的员工id列表里 过滤数据库里不存在的 即需要添加的员工 id
        Set<Long> addUserIdSet = selectedUserIdList.stream().filter(id -> !dbEmployeeIdSet.contains(id)).collect(Collectors.toSet());

        // 添加角色员工
        if (CollectionUtil.isNotEmpty(addUserIdSet)) {
            List<RoleUserEntity> roleEmployeeList = addUserIdSet.stream()
                    .map(employeeId -> new RoleUserEntity(roleId, employeeId))
                    .collect(Collectors.toList());
            saveBatch(roleEmployeeList);
        }
        return ResponseDTO.ok();
    }

    @Override
    public List<RoleVO> getRolesByUserId(Long userId) {
        return baseMapper.selectRolesByUserId(userId);
    }
}
